﻿using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Framework.Exceptions.RepositoryExceptions;
using HelperTools;
using Interfaces.Criteria;
using Interfaces.Filters;
using Interfaces.Models;
using Interfaces.Providers;
using Interfaces.Repositories;
using Interfaces.RepositoryModels.InternalModels.EconomicInformationModels;

namespace SQLRepositories.EconomicRepositories
{
    public class PairRepository : EntityBaseRepository<PairModel>, IPairRepository, IEconomicDataProvider<IEnumerable<IPair>, IPairFilter, IKeySupportedCriteria>
    {
        public PairRepository(IDBEconomicInformationServiceContext context) 
            : base(context)
        {}

        public void Create(PairModel item)
        {
            Context.PairModels.Add(item);
            Context.SaveChanges();
        }

        public PairModel GetById(Guid id)
        {
            return Context.PairModels.FirstOrDefault(x => x.Id.Equals(id));
        }

        public void Delete(Guid id)
        {
            var removedItem = Context.PairModels.FirstOrDefault(x => x.Id.Equals(id));
            if(removedItem == null)
                throw new EntityNotFoundException("Pair");
            Context.PairModels.Remove(removedItem);
            Context.SaveChanges();
        }

        public void Delete(PairModel item)
        {
            Context.PairModels.Remove(item);
            Context.SaveChanges();
        }

        public IEnumerable<PairModel> GetAll()
        {
            return Context.PairModels;
        }

        public IEnumerable<IPair> GetData(IKeySupportedCriteria criteria, IPairFilter filter)
        {

            if (filter == null)
                throw new ArgumentNullException("filter");
            if (criteria == null)
                throw new ArgumentNullException("criteria");
            
            var source = from pair in Context.PairModels where criteria.Identificators.Contains(pair.PairId) select pair;

            RepositoryMappingHelper.ResetMapping();
            RepositoryMappingHelper.CreateXChangeRateMapping();
            RepositoryMappingHelper.CreatePairMapping(criteria.IsFullLoading,filter.With(x=>x.XchangeRateFilter));

            var result = Mapper.Map<IEnumerable<PairModel>, IEnumerable<IPair>>(source);
            return filter.Filtrate(result) as IEnumerable<IPair>;

        }
    }
}
